package org.dromara.web.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.sd4324530.fastweixin.api.UserAPI;
import com.github.sd4324530.fastweixin.api.entity.UserInfo;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.GetUsersResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusiException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.domain.bo.SysMemberBo;
import org.dromara.system.domain.vo.SysAccountVo;
import org.dromara.system.domain.bo.SysAccountBo;
import org.dromara.system.domain.vo.SysMemberVo;
import org.dromara.system.enums.AppCodeEnum;
import org.dromara.system.service.ISysAccountService;
import org.dromara.system.service.ISysMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * Author: fly
 * Date: 2024/9/23
 **/
@RequiredArgsConstructor
@Slf4j
@Service
public class SysWxService {


    private final ISysAccountService sysAccountService;

    private final ISysMemberService sysMemberService;

    public void updateMpOpenIdToUser(String wxAppId, String code) {

        SysAccountVo exist = sysAccountService.getOne(new SysAccountBo().builder().wxAppId(wxAppId).build());

        if (exist != null) {
            UserAPI userAPI = new UserAPI(exist);
            GetUserInfoResponse userInfoResponse = userAPI.getUserInfo(code);
            if (StringUtils.isNotEmpty(userInfoResponse.getUnionid())) {

                List<SysMemberVo> members = sysMemberService.queryList(new SysMemberBo().builder().unionId(userInfoResponse.getUnionid()).build());
                for (SysMemberVo member : members) {
                    if (member != null) {
                        SysMemberBo memberBo = new SysMemberBo();
                        memberBo.setMemberId(member.getMemberId());
                        memberBo.setPublicId(userInfoResponse.getOpenid());
                        sysMemberService.updateByBo(memberBo);
                    }
                }
            }
        }
    }
}
